package cn.b.sky.admin.security.context;

import org.springframework.util.Assert;

public final class ThreadLocalManagementContextHolderStrategy implements ManagementContextHolderStrategy {

//~ Static fields/initializers =====================================================================================

  private static final ThreadLocal<ManagementContext> contextHolder = new ThreadLocal<ManagementContext>();

  //~ Methods ========================================================================================================

  @Override
  public void clearContext() {
      contextHolder.remove();
  }

  @Override
  public ManagementContext getContext() {
      ManagementContext ctx = contextHolder.get();

      if (ctx == null) {
          ctx = createEmptyContext();
          contextHolder.set(ctx);
      }

      return ctx;
  }

  @Override
  public void setContext(ManagementContext context) {
      Assert.notNull(context, "Only non-null ManagementContext instances are permitted");
      contextHolder.set(context);
  }

  @Override
  public ManagementContext createEmptyContext() {
    return new ManagementContextImpl();
  }

}
